package com.focus.xyz.core.utils;

import org.openqa.selenium.os.WindowsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by chenmeng on 2016/4/19.
 */
public class ProcessUtil {
    private static transient Logger logger = LoggerFactory.getLogger(ProcessUtil.class);

    public static boolean findProcess(String processname) {
        BufferedReader bufferedreader = null;
        try {
            Process proc = Runtime.getRuntime().exec(
                    "tasklist /fi \" imagename eq " + processname + " \" ");
            bufferedreader = new BufferedReader(new InputStreamReader(proc
                    .getInputStream(),"UTF-8"));
            String line = null;
            while ((line = bufferedreader.readLine()) != null) {
                if (line.contains(processname)) {
                    return true;
                }
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            if (bufferedreader != null) {
                try {
                    bufferedreader.close();
                } catch (Exception ex) {
                }
            }
        }


    }

    public static void killProcess(String processname) {
        BufferedReader bufferedreader = null;
        try {
            Process proc = Runtime.getRuntime().exec(
                    "taskkill /F /IM " + processname);
            bufferedreader = new BufferedReader(new InputStreamReader(proc
                    .getInputStream(),"UTF-8"));
            String line = null;
            while ((line = bufferedreader.readLine()) != null) {
                logger.debug(line);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (bufferedreader != null) {
                try {
                    bufferedreader.close();
                } catch (Exception ex) {
                }
            }
        }
    }

    public static void closeBrowser(String browser){
        if(Constants.IE.equals(browser)){
            WindowsUtils.tryToKillByName("iexplore.exe");
        }else if(Constants.CHROME.equals(browser)){
            WindowsUtils.tryToKillByName("chrome.exe");
        }else if(Constants.FIREFOX.equals(browser)){
            WindowsUtils.tryToKillByName("firefox.exe");
        }
    }
}
